import {debounce, throttle} from 'lodash';
interface IContentRect {
  bottom: number
  height: number
  left: number
  right: number
  top: number
  width: number
  x: number
  y: number
}

class ResizeTool {
  public ResizeObserver: any;
  constructor() {
    this.ResizeObserver = null;
  }

  init(module: any, onload: Function){
     if(!this.ResizeObserver){
       this.ResizeObserver = module;
       if(typeof onload === 'function') onload();
     }
  }

  resizeObserver(container: Element, {
    refreshMode,
    refreshRate = 50,
    onResize
  }: {
    refreshMode?: 'debounce' | 'throttle',
    refreshRate?: number,
    onResize?: (contentRect: IContentRect) => void;
  }) {
    if(!this.ResizeObserver) return;
    const resizeCallback = (entries: any[], observer: any) => {
      for (const entry of entries) {
        if (entry.target === container) {
          if (typeof onResize === 'function') onResize(entry.contentRect)

        }
      }
    }
    const ro = new this.ResizeObserver(
      refreshMode === 'debounce'
        ? debounce(resizeCallback, refreshRate)
        : refreshMode === 'throttle'
        ? throttle(resizeCallback, refreshRate)
        : resizeCallback
    );
    ro.observe(container)
    return ro;
  }
}

export default new ResizeTool();
